package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

// 购物车
@Service
@Transactional
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    // 添加购物车
    @Override
    public Cart add(Cart cartParam) {
        // 1.先查询购物车是否有此项数据
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId()); // 用户id
        qw.eq(cartParam.getDishId() != null, Cart::getDishId, cartParam.getDishId()); // 菜品id
        qw.eq(cartParam.getSetmealId() != null, Cart::getSetmealId, cartParam.getSetmealId()); // 套餐id
        Cart cart = cartMapper.selectOne(qw);

        // 2.判断
        if (cart == null) { // 不存在，新增
            cart = cartParam;
            cart.setUserId(UserHolder.get().getId()); // 补全用户信息
            cart.setNumber(1); // 补全数量
            cart.setCreateTime(new Date()); // 补全添加购物车时间
            cartMapper.insert(cart);
        } else { // 存在，数量+1，更新数据库
            cart.setNumber(cart.getNumber() + 1);
            cartMapper.updateById(cart);
        }

        // 3.返回购物车
        return cart;
    }

    //查询购物车
    @Override
    public List<Cart> list() {
        //构建条件
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId());
        List<Cart> carts = cartMapper.selectList(qw);
        //查询
        return carts;
    }

    //修改购物车
    @Override
    public Cart sub(Cart cartParam) {
        //先查询购物车
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId());//用户id
        qw.eq(cartParam.getDishId() != null, Cart::getDishId, cartParam.getDishId());//菜品id
        qw.eq(cartParam.getSetmealId() != null, Cart::getSetmealId, cartParam.getSetmealId());//套餐id
        Cart cart = cartMapper.selectOne(qw);

        //判断
        if (cart.getNumber() == 1) {//数量等于1的时候
            //删除
            cartMapper.deleteById(cart);
            cart.setNumber(0);

        } else if (cart.getNumber() > 1) {//大于1
            //数量减1
            cart.setNumber(cart.getNumber() - 1);

            cartMapper.updateById(cart);
        }

        return cart;
    }

    //清空购物车
    @Override
    public void clean() {
        //构建条键
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId,UserHolder.get().getId());
        //删除
        cartMapper.delete(qw);
    }


}
